package com.learn.service.impl;

import com.learn.entity.Users;
import com.learn.service.IUsersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class IUsersServiceImpl implements IUsersService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void deleteUser(long userId) {
        redisTemplate.delete(String.valueOf(userId));
        log.info("delete cache ok");
    }

    @Override
    public Users getUser(long userId) {
        ValueOperations<String, Users> ops = redisTemplate.opsForValue();
        Users s = ops.get(String.valueOf(userId));
        if (s == null) {
            /**
             * 这里要去查库获取值
             */
            Users users = getUsersFromDB(userId);

            ops.set(String.valueOf(users.getUserId()),users);

            return users;
        }

        return s;
    }

    private Users getUsersFromDB(long userId) {
        Users users = new Users();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("spent 1s to get user from db");
        users.setUserId(userId);
        users.setUserName("zhangsan");

        return users;
    }
}
